package com.ysh.spring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 袁胜虎 on 2022/8/30 16:33
 */
@Controller
@RequestMapping("/test")
@SessionAttributes({"requestattr","sessionattr","sessionattr2"})//这个注解的作用,当我们使用model或者modelandview保存数据的时候如果是这两个key就保存到session中
public class TestController {
    @RequestMapping("/test1")
    public String test1(HttpServletRequest request, HttpSession session){
        request.setAttribute("requestattr","liwei");
        request.getSession().setAttribute("sessionattr", "diannao");
        session.setAttribute("sessionattr2","离家出走了");
        return "/success.jsp";
    }    /**
     * 通过model可以将数据保存到request中
     * @param model
     * @return
     */
    @RequestMapping("/test2")
    public String test2(Model model){
        model.addAttribute("requestattr","rangwo");
        model.addAttribute("sessionattr","geisuoyuhang");
        model.addAttribute("sessionattr2","maihuaquan");
        return "/success.jsp";
    }
    /**
     * 在重定向的时候, model中的数据会被当做请求参数拼接到地址中,这就是和request的区别
     * @param model
     * @return
     */
    @RequestMapping("/test3")
    public String test3(Model model){
        model.addAttribute("requestattr","rangwo");
        model.addAttribute("sessionattr","geisuoyuhang");
        model.addAttribute("sessionattr2","maihuaquan");
        return "redirect:/success.jsp";
    }
    /**
     * 放数据和视图
     * @param modelAndView
     * @return
     */
    @RequestMapping("/test4")
    public ModelAndView test4(ModelAndView modelAndView){
        modelAndView.addObject("requestattr","wnagxinyu");
        modelAndView.addObject("sessionattr","wo d hao lao po ");
        modelAndView.addObject("sessionattr2","!!!!!");
        modelAndView.setViewName("/success.jsp");//设置视图的名字,就是目标的页面
        return modelAndView;
    }
    @RequestMapping("/clear")
    public String hello(SessionStatus status){
        //移出通过SessionAttributes存入的session
        status.setComplete();
        return "redirect:/success.jsp";
    }
}
